package com.jpro.module.mp.controller.admin.news;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import com.jpro.framework.common.pojo.CommonResult;
import com.jpro.module.mp.framework.mp.core.MpServiceFactory;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpMassMessageService;
import me.chanjar.weixin.mp.api.WxMpMaterialService;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.WxMpMassNews;
import me.chanjar.weixin.mp.bean.WxMpMassTagMessage;
import me.chanjar.weixin.mp.bean.draft.WxMpDraftArticles;
import me.chanjar.weixin.mp.bean.draft.WxMpDraftInfo;
import me.chanjar.weixin.mp.bean.material.WxMpNewsArticle;
import me.chanjar.weixin.mp.bean.result.WxMpMassSendResult;
import me.chanjar.weixin.mp.bean.result.WxMpMassUploadResult;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;

import static com.jpro.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.jpro.framework.common.pojo.CommonResult.success;
import static com.jpro.module.mp.enums.ErrorCodeConstants.NEWS_SEND_FAIL;
import static me.chanjar.weixin.common.api.WxConsts.MaterialType.IMAGE;

@Slf4j
@Tag(name = "管理后台 - 公众号群发图文控制器")
@RestController
@RequestMapping("/mp/news")
@Validated
public class MpNewsController {

    @Resource
    private MpServiceFactory mpServiceFactory;

    @PostMapping("/send")
    @Operation(summary = "群发")
    @Parameter(name = "accountId", description = "公众号账号的编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('mp:draft:create')")
    public CommonResult<String> sendNews(@RequestParam("accountId") Long accountId,
                                         @RequestParam("mediaId") String mediaId) {
        WxMpService mpService = mpServiceFactory.getRequiredMpService(accountId);
        try {
            final WxMpDraftInfo wxMpDraftInfo = mpService.getDraftService().getDraft(mediaId);
            final WxMpMassMessageService massMessageService = mpService.getMassMessageService();
            final WxMpMaterialService materialService = mpService.getMaterialService();

            WxMpMassNews news = new WxMpMassNews();
            final List<WxMpDraftArticles> newsItems = wxMpDraftInfo.getNewsItem();
            for (WxMpDraftArticles newsItem : newsItems) {
                WxMpNewsArticle article = new WxMpNewsArticle();
                article.setTitle(newsItem.getTitle());
                article.setContent(newsItem.getContent());
                final InputStream inputStream = materialService.materialImageOrVoiceDownload(newsItem.getThumbMediaId());
                File file = FileUtil.newFile(FileUtil.getTmpDirPath() + UUID.randomUUID().toString() + ".jpg");
                IoUtil.copy(inputStream, new FileOutputStream(file));
                final WxMediaUploadResult wxMediaUploadResult = materialService.mediaUpload(IMAGE, file);
//                final WxMediaUploadResult wxMediaUploadResult = materialService.mediaUpload(IMAGE, WxConsts.MediaFileType.IMAGE, inputStream);
                article.setThumbMediaId(wxMediaUploadResult.getMediaId());
                article.setShowCoverPic(true);
                article.setAuthor(newsItem.getAuthor());
                article.setContentSourceUrl(newsItem.getContentSourceUrl());
                article.setDigest(newsItem.getDigest());
                news.addArticle(article);
                file.deleteOnExit();
            }
            WxMpMassUploadResult massUploadResult = massMessageService.massNewsUpload(news);

            WxMpMassTagMessage mpMassTagMessage = new WxMpMassTagMessage();
            mpMassTagMessage.setMsgType(WxConsts.MassMsgType.MPNEWS);
            mpMassTagMessage.setMediaId(massUploadResult.getMediaId());
            //暂时群发全部，不按tag分组群发
            mpMassTagMessage.setSendAll(true);
            WxMpMassSendResult massResult = massMessageService.massGroupMessageSend(mpMassTagMessage);
//            WxMpMassOpenIdsMessage massMessage = new WxMpMassOpenIdsMessage();
//            massMessage.setMsgType(WxConsts.MassMsgType.MPNEWS);
//            massMessage.setMediaId(massUploadResult.getMediaId());
//            massMessage.getToUsers().add(openid);
//            WxMpMassSendResult massResult = massMessageService.massOpenIdsMessageSend(mpMassTagMessage);
            final String errorCode = massResult.getErrorCode();
            log.info("sendNews result->{},{},{},{}", errorCode, massResult.getErrorMsg(), massResult.getMsgId(), massResult.getMsgDataId());
            if (!"0".equals(errorCode)) {
                return CommonResult.error(NEWS_SEND_FAIL.getCode(), String.format("微信返回:code->%s message->%s", massResult.getErrorCode(), massResult.getErrorMsg()));
            }
            return success(massResult.getMsgId());
        } catch (WxErrorException e) {
            throw exception(NEWS_SEND_FAIL, e.getError().getErrorMsg());
        } catch (FileNotFoundException e) {
            throw exception(NEWS_SEND_FAIL, e.getMessage());
        }
    }

}
